package com.xcc.shopanim;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.xcc.shopanim.utils.Logger;
import com.xcc.shopanim.utils.MemoryLeakUtil;
import com.xcc.shopanim.utils.QMUIStatusBarHelper;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

/**
 * Created by Administrator on 2017/12/19.
 */
public class SimpleBaseActivity<T extends BaseContract.Presenter> extends AppCompatActivity {
    protected T presenter;
    public boolean isPause, isDestroy;
    protected NetWorkStateReceiver netWorkStateReceiver;
    protected boolean openWorkStateReceiver = false;

    //是否登录
    /*public boolean isLogin() {
        return isLogin(true);
    }

    public boolean isLogin(boolean openLogin) {
        //强制登录
        //if ((UserConfig.getGestureHint() & 32) == 32) openLogin = true;
        boolean login = ShopApp.getInstance().isLogin();
        if (openLogin && !login) {
            NewLoginActivity.open(getActivity());
        }
        return login;
    }*/

    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O && isTranslucentOrFloating()) {//这是解决一个安卓8.0，透明bug
            boolean result = fixOrientation();
        }
        super.onCreate(savedInstanceState);
        isF = true;
        if (BuildConfig.DEBUG) Logger.out("--xcc--onCreate();--");
    }

    private boolean isTranslucentOrFloating() {
        boolean isTranslucentOrFloating = false;
        try {
            int[] styleableRes = (int[]) Class.forName("com.android.internal.R$styleable").getField("Window").get(null);
            final TypedArray ta = obtainStyledAttributes(styleableRes);
            Method m = ActivityInfo.class.getMethod("isTranslucentOrFloating", TypedArray.class);
            m.setAccessible(true);
            isTranslucentOrFloating = (boolean) m.invoke(null, ta);
            m.setAccessible(false);
        } catch (Exception e) {
            if (BuildConfig.DEBUG) e.printStackTrace();
        }
        return isTranslucentOrFloating;
    }

    private boolean fixOrientation() {
        try {
            Field field = Activity.class.getDeclaredField("mActivityInfo");
            field.setAccessible(true);
            ActivityInfo o = (ActivityInfo) field.get(this);
            o.screenOrientation = -1;
            field.setAccessible(false);
            return true;
        } catch (Exception e) {
            if (BuildConfig.DEBUG) e.printStackTrace();
        }
        return false;
    }

    //查找fragment， 移除掉
    public void removeFragment(Bundle savedInstanceState) {
        if (savedInstanceState == null) return;
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fm.beginTransaction();
        List<Fragment> fragments = fm.getFragments();
        Fragment fragment;
        for (int i = 0; i < fragments.size(); i++) {
            fragment = fragments.get(i);
            if (fragment == null) continue;
            fragmentTransaction.remove(fragment);
            if (BuildConfig.DEBUG) {
                Logger.out(fragment.getClass().getName());
            }
        }
        if (fragments.size() > 0)
            fragmentTransaction.commitAllowingStateLoss();
    }

    protected void onResume() {
        super.onResume();
        isPause = false;
        if (openWorkStateReceiver) {
            if (netWorkStateReceiver == null) {
                netWorkStateReceiver = new NetWorkStateReceiver();
            }
            IntentFilter filter = new IntentFilter();
            filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
            registerReceiver(netWorkStateReceiver, filter);
        }
    }

    protected void onPause() {
        super.onPause();
        isPause = true;
        if (netWorkStateReceiver != null) unregisterReceiver(netWorkStateReceiver);
        netWorkStateReceiver = null;
    }

    protected void onStop() {
        super.onStop();
    }

    protected void onDestroy() {
        if (presenter != null) presenter.onDestroy();
        presenter = null;
        isDestroy = true;
        super.onDestroy();
        MemoryLeakUtil.fixInputMethodMemoryLeak(this);
        //ShopApp.getRefWatcher().watch(this);
    }

    //渗透式，状态栏透明
    protected void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
            View decorView = getWindow().getDecorView();
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }
    }

    public void recreate() {
        Intent intent = getIntent();
        intent.addFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
        startActivity(intent);
        overridePendingTransition(0, 0);
        finish();
    }

    protected boolean isF = true;

    public void onWindowFocusChanged(boolean hasFocus) {
        if (BuildConfig.DEBUG) Logger.out("--xcc--onWindowFocusChanged();--");
        if (isF && hasFocus) {
            isF = false;
            if (BuildConfig.DEBUG) Logger.out("--xcc--asynRun();--");
            asynRun();
        }
    }

    protected void asynRun() {
    }

    public void setStatusBarTextColor(boolean isWhite) {
        if (isWhite) {
            QMUIStatusBarHelper.setStatusBarDarkMode(getActivity());//白色
        } else QMUIStatusBarHelper.setStatusBarLightMode(getActivity());//黑色
    }

    public SimpleBaseActivity getActivity() {
        return this;
    }

    protected long oldTouchTime;
    public boolean skipOldTouch;

    //防止短时间内多次启动同一个Activity
    @SuppressLint("RestrictedApi")
    public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
        if (skipOldTouch) {
            super.startActivityForResult(intent, requestCode, options);
        } else {
            long time = System.currentTimeMillis();
            if (time - oldTouchTime > 500) {
                oldTouchTime = time;
                super.startActivityForResult(intent, requestCode, options);
            }
        }
    }

    protected void onNetworkType(String networkType) {
    }

    public class NetWorkStateReceiver extends BroadcastReceiver {
        public void onReceive(Context context, Intent intent) {
            if (context == null) return;
            onNetworkType(BaseActivity.getNetworkType(context));
        }
    }
}
